//
//  AddAnswerVC.m
//  MyProject
//
//  Created by jiaming yan on 2018/5/15.
//  Copyright © 2018年 yanjiaming. All rights reserved.
//

#import "AddAnswerVC.h"
#import "NSUDManager.h"
#import "EaseRecordView.h"
#import "EMCDDeviceManager.h"
#import "IQTextView.h"
#import <QiniuSDK.h>
#import <AVFoundation/AVFoundation.h>
#import "NSUDManager.h"
#import "EMCDDeviceManager+Media.h"
#import "EMVoiceConverter.h"
#import "EMAudioPlayerUtil.h"

@interface AddAnswerVC ()
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UIImageView *userHeadImageView;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *userNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *typeLabel;
@property (weak, nonatomic) IBOutlet UIButton *sameQuestionButton;
@property (weak, nonatomic) IBOutlet UILabel *tagLabel;

@property (weak, nonatomic) IBOutlet UIView *timeBackView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *timeViewHeight;
@property (weak, nonatomic) IBOutlet UIButton *recordButton;
@property (strong, nonatomic) EaseRecordView *recordView;


@property (weak, nonatomic) IBOutlet UIButton *typeButton1;
@property (weak, nonatomic) IBOutlet UIButton *typeButton2;

@property (weak, nonatomic) IBOutlet UIView *recordBackView;
@property (weak, nonatomic) IBOutlet UIView *playBackView;
@property (weak, nonatomic) IBOutlet UIView *wordBackView;
@property (weak, nonatomic) IBOutlet IQTextView *wordTextView;
@property (weak, nonatomic) IBOutlet UILabel *voiceLengthLabel;

@property (copy, nonatomic) NSString *anwserType;
@property (copy, nonatomic) NSString *voiceUrl;
@property (assign, nonatomic) NSInteger voiceLength;
@property (strong, nonatomic) AVPlayer * player;

@property (weak, nonatomic) IBOutlet UIButton *refuseButton;
@property (weak, nonatomic) IBOutlet UIButton *refuseButton1;

@end

@implementation AddAnswerVC
- (UIView *)recordView
{
    if (_recordView == nil) {
        _recordView = [[EaseRecordView alloc] initWithFrame:CGRectMake(90, 130, 140, 140)];
    }
    
    return _recordView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"问答详情";
    self.wordTextView.placeholder = @"请输入您的回答内容（20-300字）";
    self.anwserType = @"ANWSER_TYPE_SOUND";
    [self loadViewData];
    [self.recordButton addTarget:self action:@selector(recordButtonTouchDown) forControlEvents:UIControlEventTouchDown];
    
    [self.recordButton addTarget:self action:@selector(recordButtonTouchDragExit) forControlEvents:UIControlEventTouchDragExit];
    [self.recordButton addTarget:self action:@selector(recordButtonTouchDragEnter) forControlEvents:UIControlEventTouchDragEnter];
    [self.recordButton addTarget:self action:@selector(recordButtonTouchUpOutside) forControlEvents:UIControlEventTouchUpOutside];
    [self.recordButton addTarget:self action:@selector(recordButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.recordButton addTarget:self action:@selector(recordButtonTouchCancel) forControlEvents:UIControlEventTouchCancel];
    
    
}
- (void)recordButtonTouchDown
{
    EaseRecordView *tmpView = self.recordView;
    tmpView.center = CGPointMake(self.view.center.x, self.view.center.y-100);
    [self.view addSubview:tmpView];
    [self.view bringSubviewToFront:self.recordView];
    int x = arc4random() % 100000;
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSString *fileName = [NSString stringWithFormat:@"%d%d",(int)time,x];
    [self.recordView recordButtonTouchDown];
    [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:fileName completion:^(NSError *error)
     {
         if (error) {
//             NSLog(@"%@",NSEaseLocalizedString(@"message.startRecordFail", @"failure to start recording"));
//             _isRecording = NO;
         }
     }];
}
- (IBAction)rerecordClick:(id)sender {
    self.voiceUrl = @"";
    self.voiceLength = 9;
    self.playBackView.hidden = YES;
    self.recordBackView.hidden = NO;
    self.wordBackView.hidden = YES;
}

- (void)recordButtonTouchUpOutside
{
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
    if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
        [(EaseRecordView *)self.recordView recordButtonTouchUpOutside];
    }
    [self.recordView removeFromSuperview];
    
//    _isRecording = NO;
}

- (void)recordButtonTouchUpInside
{
    self.recordButton.enabled = NO;
    if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
        [(EaseRecordView *)self.recordView recordButtonTouchUpInside];
    }
    [self.recordView removeFromSuperview];
    __weak typeof(self) weakSelf = self;
    [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
        if (!error) {
            EMCDDeviceManager *manager =[EMCDDeviceManager sharedInstance] ;
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSString *wavFilePath = [[recordPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"wav"];
            if ([EMVoiceConverter isMP3File:recordPath]) {
                wavFilePath = recordPath;
            } else {
                if (![fileManager fileExistsAtPath:wavFilePath]) {
                    BOOL covertRet = [manager convertAMR:recordPath toWAV:wavFilePath];
                    if (!covertRet) {
                        
                        return ;
                    }
                }
            }
            
            weakSelf.voiceUrl = wavFilePath;
            weakSelf.voiceLength = aDuration;
            weakSelf.voiceLengthLabel.text = [CommonUtils timeIntervalWithDate:aDuration];
            weakSelf.playBackView.hidden = NO;
            weakSelf.recordBackView.hidden = YES;
            weakSelf.wordBackView.hidden = YES;
        }
        else {
            [self showProgressWithView:self.view animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self hideProgress:self.view animated:YES];
            });
        }
    }];
//    _isRecording = NO;
    self.recordButton.enabled = YES;
}

- (void)recordButtonTouchDragExit
{
     [(EaseRecordView *)self.recordView recordButtonDragOutside];
}

- (void)recordButtonTouchDragEnter
{
    if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
        [(EaseRecordView *)self.recordView recordButtonDragInside];
    }
}

- (void)recordButtonTouchCancel
{
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
    if ([self.recordView isKindOfClass:[EaseRecordView class]]) {
        [(EaseRecordView *)self.recordView recordButtonTouchUpOutside];
    }
    [self.recordView removeFromSuperview];
    
//    _isRecording = NO;
}





-(void)loadViewData{
    self.sameQuestionButton.layer.borderColor = UIColorFromRGB(0X00C6D5).CGColor;
    self.sameQuestionButton.layer.borderWidth = 1;
    self.sameQuestionButton.layer.cornerRadius = 10;
    
    self.contentLabel.text = self.model.content;
    [self.contentLabel sizeToFit];
    [self.userHeadImageView sd_setImageWithURL:[NSURL URLWithString:ImageURL(self.model.publisherHeadImg)] placeholderImage:IMAGE(@"默认图")];
    self.userNameLabel.text = self.model.publisher;
    self.priceLabel.text = [NSString stringWithFormat:@"赏金￥%@",self.model.bonus];
    self.tagLabel.text = [NSString stringWithFormat:@"#%@#",self.model.relatedTag];
    self.timeLabel.text = [NSString stringWithFormat:@"%@结束",self.model.closeTime];
    if ([self.model.questionType isEqualToString:@"QUESTION_TYPE_DESIGNATED"]) {
        self.refuseButton.hidden = NO;
        self.refuseButton1.hidden = NO;
    }else{
        self.refuseButton.hidden = YES;
        self.refuseButton1.hidden = YES;
    }
    
    UserModel *user = [NSUDManager currentUser];
    
    
    if (self.model.isClose) {
        /**已关闭*/
        self.typeLabel.hidden = NO;
        self.sameQuestionButton.hidden = YES;
        self.timeBackView.hidden = YES;
        self.timeViewHeight.constant = 9;
    }else{
        self.typeLabel.hidden = YES;
        self.sameQuestionButton.hidden = NO;
        self.timeBackView.hidden = NO;
        self.timeViewHeight.constant = 34;
        if ([user.userId isEqualToString:self.model.publisherId]) {
            /**我本人发布的*/
            self.sameQuestionButton.hidden = YES;
        }else{
            
        }
    }
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)typeButtonClick:(UIButton *)sender {
    self.voiceLength = 0;
    self.voiceUrl = @"";
    if (sender == self.typeButton1) {
        self.playBackView.hidden = YES;
        self.recordBackView.hidden = NO;
        self.wordBackView.hidden = YES;
        self.anwserType = @"ANWSER_TYPE_SOUND";
        [self.typeButton1 setTitleColor:UIColorFromRGB(0x00C6D5) forState:UIControlStateNormal];
        [self.typeButton2 setTitleColor:UIColorFromRGB(0XA5B9C2) forState:UIControlStateNormal];
    }else{
        self.playBackView.hidden = YES;
        self.recordBackView.hidden = YES;
        self.wordBackView.hidden = NO;
        self.anwserType = @"ANWSER_TYPE_WORDS";
        [self.typeButton1 setTitleColor:UIColorFromRGB(0XA5B9C2) forState:UIControlStateNormal];
        [self.typeButton2 setTitleColor:UIColorFromRGB(0x00C6D5) forState:UIControlStateNormal];
    }
}
- (IBAction)refuseClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)submitClick:(id)sender {
    if ([self.anwserType isEqualToString:@"ANWSER_TYPE_SOUND"]) {
        /**语音*/
        if (self.voiceLength == 0 || self.voiceUrl.length == 0) {
            ALERT_VIEW(@"请完成录音后提交");
            return;
        }
        __weak typeof(self) weakSelf = self;
        [self showProgressWithView:self.view animated:YES];
        [YJMSendRequest postDataWithParameters:@{} url:@"common/getQiuNiuUpToken" result:^(NSDictionary *result, NSError *error) {
            result = [CommonUtils decryptDicWithResult:result];
            [self hideProgress:self.view animated:YES];
            if([result[@"result"] integerValue] == 1)
            {
                NSString *token = result[@"data"][@"upToken"];
                //华北
                QNConfiguration *config = [QNConfiguration build:^(QNConfigurationBuilder *builder) {
                    builder.zone = [QNFixedZone zone1];
                }];
                QNUploadManager *upManager = [[QNUploadManager alloc] initWithConfiguration:config];
//                [upManager putData:imageData key:nil token:token complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                [upManager putFile:self.voiceUrl key:nil token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp){
                    NSDictionary *dic = @{@"questionId":[NSString stringWithFormat:@"%@",self.model.questionId],@"anwserType":self.anwserType,@"soundKey":resp[@"key"],@"soundLength":[NSString stringWithFormat:@"%zd",self.voiceLength*1000]};
                    
                    [self requestWith:dic];
                }option:nil];
                    
                    
                
            }else{
                
                
                [CommonUtils showToast:[result objectForKey:@"msg"]];
            }
            
        }];
    }else{
        /**文字*/
        if (self.wordTextView.text.length == 0) {
            ALERT_VIEW(@"请输入内容");
            return;
        }
        NSDictionary *dic = @{@"questionId":[NSString stringWithFormat:@"%@",self.model.questionId],@"anwserType":self.anwserType,@"content":self.wordTextView.text};
        [self requestWith:dic];
    }
   
    
}
-(void)requestWith:(NSDictionary *)paramter{
    __weak typeof(self) weakSelf = self;
    [self showProgressWithView:self.view animated:YES];
    [YJMSendRequest postDataWithParameters:paramter url:@"question/releaseAnwser" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        [self hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshHelpList" object:nil];
        }else{
            
            
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
        
    }];
}
- (IBAction)playButtonClick:(id)sender {
    
    [EMAudioPlayerUtil asyncPlayingWithPath:self.voiceUrl
                                 completion:^(NSError *error)
     {
         
     }];
}
-(IBAction)sameQuestionClick:(id)sender {
    __weak typeof(self) weakSelf = self;
    [self showProgressWithView:self.view animated:YES];
    [YJMSendRequest postDataWithParameters:@{@"questionId":[NSString stringWithFormat:@"%@",self.model.questionId]} url:@"question/releaseSameQuestion" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        [self hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            ALERT_VIEW(@"同问完成");
            
        }else{
            
            
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
        
    }];
}
- (IBAction)refuseButtonClick:(id)sender {
    __weak typeof(self) weakSelf = self;
    [self showProgressWithView:self.view animated:YES];
    [YJMSendRequest postDataWithParameters:@{@"questionId":[NSString stringWithFormat:@"%@",self.model.questionId]} url:@"question/reiect" result:^(NSDictionary *result, NSError *error) {
        result = [CommonUtils decryptDicWithResult:result];
        [self hideProgress:self.view animated:YES];
        if([result[@"result"] integerValue] == 1)
        {
            [weakSelf.navigationController popViewControllerAnimated:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshHelpList" object:nil];
        }else{
            
            
            [CommonUtils showToast:[result objectForKey:@"msg"]];
        }
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
